package com.gd.deron.smartrobot.baobao;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.gd.deron.smartrobot.baobao.app.MyApplication;
import com.gd.deron.smartrobot.baobao.db.DatabaseAsrDao;
import com.gd.deron.smartrobot.baobao.db.DatabaseAsrOfflineBean;
import com.gd.deron.smartrobot.baobao.hci.AccountInfo;
import com.gd.deron.smartrobot.baobao.hci.HciCloudTtsHelper;
import com.gd.deron.smartrobot.baobao.info.RobotInfo;
import com.gd.deron.smartrobot.baobao.info.VoiceTitle;
import com.gd.deron.smartrobot.baobao.service.AsrService;
import com.gd.deron.smartrobot.baobao.service.BluetoothBleService;
import com.gd.deron.smartrobot.baobao.service.LocationService;
import com.gd.deron.smartrobot.baobao.service.WakeService;
import com.gd.deron.smartrobot.baobao.tranlate.BaiduTranslate;
import com.gd.deron.smartrobot.baobao.utils.BlueTools;
import com.gd.deron.smartrobot.baobao.utils.ChineseUtil;
import com.gd.deron.smartrobot.baobao.utils.Config;
import com.gd.deron.smartrobot.baobao.utils.FileUtils;
import com.gd.deron.smartrobot.baobao.utils.FucUtil;
import com.gd.deron.smartrobot.baobao.utils.InstructionUtil;
import com.gd.deron.smartrobot.baobao.utils.JsonParser;
import com.gd.deron.smartrobot.baobao.utils.NetworkUtils;
import com.gd.deron.smartrobot.baobao.utils.PlayMusicTool;
import com.gd.deron.smartrobot.baobao.utils.SharedPreferenceUtil;
import com.gd.deron.smartrobot.baobao.utils.ToastUtils;
import com.gd.deron.smartrobot.baobao.utils.WifiAdminUtils;
import com.gd.deron.smartrobot.baobao.utils.WifiConnectUtils;
import com.gd.deron.smartrobot.baobao.wifi.ChatMessage;
import com.gd.deron.smartrobot.baobao.wifi.Global;
import com.gd.deron.smartrobot.baobao.wifi.SocketClient;
import com.gd.deron.smartrobot.baobao.wifi.SocketClient.ClientMsgListener;
import com.gd.deron.smartrobot.baobao.wifi.SocketServer;
import com.gd.deron.smartrobot.baobao.wifi.SocketServer.ServerMsgListener;
import com.gd.deron.smartrobot.baobao.wifi.WifiHotManager;
import com.gd.deron.smartrobot.baobao.wifi.WifiHotManager.OpretionsType;
import com.gd.deron.smartrobot.baobao.wifi.WifiHotManager.WifiBroadCastOperations;
import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechSynthesizer;
import com.sinovoice.hcicloudsdk.api.HciCloudSys;
import com.sinovoice.hcicloudsdk.common.AuthExpireTime;
import com.sinovoice.hcicloudsdk.common.HciErrorCode;
import com.sinovoice.hcicloudsdk.common.InitParam;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends BaseActivity implements WifiBroadCastOperations, OnTouchListener {
	protected static final String TAG = "MainActivity";
	private ImageView mImageView;
	private ImageView view;
	private Dialog recordIndicator;
	private SpeechSynthesizer mTts;
	private String robotId = "";
	private MediaPlayer mp = new MediaPlayer();
	private LocationService locationService;
	private AudioManager mAudioManager;
	// 默认云端发音人
	public static String voicerCloud = "nannan";
	private String speed = "85";// 语速
	private String pitch = "50";// 语调
	private String volume = "100";// 音量

	private Handler serverHandler;
	private Handler clientHandler;
	private Gson gson;
	private boolean isContectWifi = false;
	private WifiAdminUtils mWifiAdmin;
	private WifiHotManager wifiHotM;
	private String wifiName;
	private String wifiPas;
	private String wifiNameShare;
	private String wifiPasShare;
	private SocketClient client;

	private SocketServer server;
	private boolean connected;
	private boolean isQueAns;;
	private List<ScanResult> wifiList;
	private DatabaseAsrDao mAsrDao;
	private StringBuffer mBuffer = new StringBuffer();
	private StringBuffer mBufferPlayTts = new StringBuffer();
	
	private TextView statusText;
	private TextView idText;
	//private String robotName = null;
	/** 接收广播 */
	public BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			switch (action) {
			case Config.CON_SUCCESS:
				mHandler.sendEmptyMessage(0x11);
				break;
			case Config.DISCONNECTED:
			case Config.SHOUDONG_DUANKAI:
				mHandler.sendEmptyMessage(0x12);
				break;
			case Config.FIND_DEVICE:
				mHandler.sendEmptyMessage(0x13);
				break;
			case Config.CURRENT_ADDRESS:
				mHandler.sendEmptyMessage(0x14);
				break;
			case Config.ASR_RESULT:
				Message message = Message.obtain();
				message.what = 0x15;
				message.obj = intent.getStringExtra("data");
				mHandler.sendMessage(message);
				break;
			case Config.ASR_VOLUME:
				BlueTools.sendData(InstructionUtil.LIGTH_LEFT_RIGHT_ONLY_ONE);
				Message message2 = Message.obtain();
				message2.what = 0x16;
				message2.arg1 = intent.getIntExtra("data", 0);
				mHandler.sendMessage(message2);
				break;
			case Config.ASR_ERROR:
				Message msg= Message.obtain();
				msg.what = 0x17;
				msg.arg1 = intent.getIntExtra("data",0);
				mHandler.sendMessage(msg);
				break;
			case Config.START_ASR:
				mHandler.sendEmptyMessage(0x18);
				break;
			case Config.STOP_ASR://Config.ASR_ANSWER
				mHandler.sendEmptyMessage(0x19);
				break;
			case Config.START_ASR_COPY:
				mHandler.sendEmptyMessage(0x21);
				break;
			case Config.STOP_ASR_COPY:
				mHandler.sendEmptyMessage(0x22);
				break;
			case Config.SUBMIT_QUESTION_ANSWER:
				mHandler.sendEmptyMessage(0x23);
				break;
			case Config.VOICE:
				mHandler.sendEmptyMessage(0x24);
				break;
			case Config.AIJIA_XINGXING:
				mHandler.sendEmptyMessage(0x25);
				break;
			case Config.AIJIA_HELLO:
			case Config.WAKE_ROBOT_ONLINE:
				mHandler.sendEmptyMessage(0x26);
				break;
			case Config.AIJIA_NIHAO:
			case Config.WAKE_ROBOT_OFFLINE:
				mHandler.sendEmptyMessage(0x27);
				break;
			case Config.ASR_ANSWER:
				mHandler.sendEmptyMessage(0x28);
				break;
			case Config.CLEAR_ARS_SQL:
				mHandler.sendEmptyMessage(0x29);
				break;
			case Config.TOUCH_DOWN:
				mHandler.sendEmptyMessage(0x30);
				break;
			case Config.TOUCH_UP:
				mHandler.sendEmptyMessage(0x31);
				break;
			case Config.PLAY_TTS:
				mHandler.sendEmptyMessage(0x32);
				break;
			default:
				break;
			}

		}

	};
//	private BluetoothBleService bleService;
//	private ServiceConnection Con = new ServiceConnection() {
//		@Override
//		public void onServiceConnected(ComponentName name, IBinder service) {
//			bleService = ((BluetoothBleService.BLEBinder) service).getService();
//			MyApplication.bleService = bleService;
//			if (!bleService.initialize()) {
//				Log.e(TAG, "蓝牙初始化失败");
//			} else {
//				// 1秒后开始连接血压计蓝牙
//				new Thread(new Runnable() {
//					@Override
//					public void run() {
//						if (MyApplication.bleService != null) {
//							Log.e(TAG, ">>>>>>>>>>>>.开始搜索单片机蓝牙");
//							MyApplication.bleService.startTimer();// 开始搜索蓝牙
//						}
//					}
//				}).start();
//			}
//		}
//
//		@Override
//		public void onServiceDisconnected(ComponentName name) {
//			bleService = null;
//		}
//	};
	private AsrService asrService;
	private ServiceConnection ConAsr = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			asrService = ((AsrService.BLEBinder) service).getService();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			asrService = null;
		}
	};
	private WakeService wakeService;
	private ServiceConnection ConWake = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			wakeService = ((WakeService.MyBinder) service).myService();
			MyApplication.wakeService = wakeService;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			wakeService = null;
		}
	};
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0x11:// 成功
				Log.e(TAG, "设备连接成功>>");
				Toast.makeText(MainActivity.this, "设备连接成功>>", 0).show();
				if(statusText!=null)
					statusText.setText("设备连接成功");
				PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_device_connected);
				break;
			case 0x12:// 断开
				Log.e(TAG, "设备断开了>>");
				if(statusText!=null)
					statusText.setText("设备连接断开");
				break;
			case 0x13:// 发现设备
				Log.e(TAG, "设备找到了>>");
				if (MyApplication.myDevice != null) {
					if (!MyApplication.isConnect && MyApplication.myDevice != null) {// 获取设备地址并连接
						Log.e(TAG, "单片机开始连接" + MyApplication.myDevice.getAddress());
						boolean bool = MyApplication.bleService.connect(MyApplication.myDevice.getAddress());
						Log.e(TAG, "连接" + bool);
					}
				}
				if(statusText!=null)
					statusText.setText("设备连接中");
				break;
			case 0x14://
				locationService.start();
				break;
			case 0x15://
				String result = (String) msg.obj;
				asrResultParse(result);
				wakeService.startWakeAiJia();
				break;
			case 0x16://
				int volume = msg.arg1;
				if (view == null)
					return;
				if (volume >= 0 && volume <= 5)
					view.setImageResource(R.drawable.voice_01);
				else if (volume >= 5 && volume <= 10)
					view.setImageResource(R.drawable.voice_02);
				else if (volume >= 10 && volume <= 15)
					view.setImageResource(R.drawable.voice_03);
				else if (volume >= 15 && volume <= 20)
					view.setImageResource(R.drawable.voice_04);
				else if (volume >= 20 && volume <= 25)
					view.setImageResource(R.drawable.voice_05);
				else
					view.setImageResource(R.drawable.voice_06);
				break;
			case 0x17://
				// mTts.startSpeaking("爱佳没听懂哦", null);
				if(msg.arg1==ErrorCode.ERROR_NO_NETWORK){
					playHciTts("没有网络");
				}else if(msg.arg1==ErrorCode.ERROR_NETWORK_TIMEOUT){
					playHciTts("连接网络超时");
				}else{
					PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.error);
				}
				wakeService.startWakeAiJia();
				break;
			case 0x18:// 按下  红色大按键
				startUnderstanding();
				break;
			case 0x19:// 松开 红色大按键
				if (NetworkUtils.isWifiConnected(MainActivity.this))
					PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.stop);
				Log.e(TAG, "松开");
				break;
			case 0x21:// 按下 白色小按键
				//停止对话
				PlayMusicTool.close();//停止音乐播放
				stopMp();//停止在线语音的点歌  的音乐播放
				stopTts();//停止在线语音的语音合成
				if(MyApplication.mHciCloudTtsHelper!=null)
					MyApplication.mHciCloudTtsHelper.stopHciTts();//停止离线语音的语音合成
				BlueTools.sendData(InstructionUtil.AIJIA_STOP);	//停止走动			
				if(asrService!=null){
					asrService.stopUnderstanding();//
					asrService.cancelUnderstanding();
				}
				
				if(wakeService!=null){
					if(!wakeService.isWake())
						wakeService.startWakeAiJia();
				}
				break;
			case 0x22:// 松开 白色小按键
				if(!wakeService.isWake())
					wakeService.startWakeAiJia();
				break;
			case 0x20://
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_baobao_app);
					}
				}, 5000);

				break;
			case 0x23://收到平板端的信息
				
				mBuffer.append(MyApplication.ANSWERANDQUESTION);
				if(!isQueAns){
					isQueAns = true;
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							try {
								if (mBuffer != null) {
									String receiverResult = mBuffer.toString();
									if(ChineseUtil.isMessyCode(receiverResult)){//判断回答是否是乱码
										Log.e(">>>>>>>", receiverResult);
										PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.error);
										mBuffer.setLength(0);
										isQueAns =false;
										ToastUtils.show(MainActivity.this, "乱码了");
										return;
									}
									if(receiverResult.length() > 0&&receiverResult.startsWith("WIFI=")){//接收的是wifi 和密码  进行wifi连接操作
										wifiName = receiverResult.substring(5, receiverResult.indexOf(":"));
										wifiPas = receiverResult.substring(receiverResult.indexOf(":") + 1);
										ToastUtils.show(MainActivity.this, "wifi="+wifiName+">>"+"密码="+wifiPas);
										Log.e("正在连接wifi>>>>>>>", "wifi="+wifiName+">>"+"密码="+wifiPas);
										startConnectWifi(wifiName,wifiPas);
										mBuffer.setLength(0);
										isQueAns =false;
									}else{//接收的是问题 和答案  进行语音库的录入
										String que = receiverResult.substring(0, receiverResult.indexOf(":"));
										String ans = receiverResult.substring(receiverResult.indexOf(":") + 1);
										Log.e(">>>>>>>", "==提问=" + que+"==答案=" + ans);
										PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.entertap);
										
										if (mAsrDao.findQuestToAnswer(que) != null) {
											mAsrDao.updateQuestAndAnswer(que, ans);
											ToastUtils.show(MainActivity.this, "提问:" + que + "答案:" + ans);
											mBuffer.setLength(0);
											isQueAns =false;
											statusText.setText("bluetooth="+receiverResult);
											playHciTts("更新成功");
											return;
										}
										ToastUtils.show(MainActivity.this, receiverResult);
										//mTts.startSpeaking("新增成功!", null);
										mAsrDao.addQuestAndAnswer(que, ans);
										writeNowTxt(que);//加入提问到call中
										mBuffer.setLength(0);
										isQueAns =false;
										playHciTts("新增成功");
										statusText.setText("bluetooth="+"提问:" + que + "  答案:" + ans);
									}
									
								}
							} catch (Exception e) {
								Log.e(TAG, e.toString());
								mBuffer.setLength(0);
								isQueAns =false;
								ToastUtils.show(MainActivity.this,e.toString());
							}
						}
					}, 2000);
				}
				
				break;
			case 0x24:
				PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.boing);
				break;
			case 0x25://爱佳醒醒
				//Toast.makeText(MainActivity.this, "爱佳醒醒", 0).show();
				//break;
			case 0x26://哈喽爱佳
				startUnderstanding() ;
				break;
			case 0x27://爱佳你好
				wakeService.stopWakeAiJia();
				startOfflineAsr();
				break;
			case 0x28://新增的语音问答   离线识别的结果  采用离线合成 进行合成发音
				playHciTts(MyApplication.ASR);
				break;
			case 0x29://此处为测试功能，删除掉所有的新增数据
				playHciTts("清除新增语音数据");
				mAsrDao.deleteAllByQuest();
				//将sd卡下的call.bnf 文件重新覆盖
   			 	FileUtils.wridCalltoSd(FucUtil.readFile(MainActivity.this, "call.bnf", "utf-8"),false);
				break;
			case 0x30://触摸按下
				playHciTts("我是女生，别摸我！");
				break;
			case 0x31://触摸松开
				
				break;
			case 0x32:
				mBufferPlayTts.append(MyApplication.ANSWERANDQUESTION);
				if(!isQueAns){
					isQueAns = true;
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							if (mBufferPlayTts != null) {
								String receiverResult = mBufferPlayTts.toString();
								if(ChineseUtil.isMessyCode(receiverResult)){//判断回答是否是乱码
									Log.e(">>>>>>>", receiverResult);
									PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.error);
									mBufferPlayTts.setLength(0);
									isQueAns =false;
									ToastUtils.show(MainActivity.this, "乱码了");
									return;
								}
								if(receiverResult.length() > 0&&receiverResult.startsWith("hello:")){
									String tts = receiverResult.substring(receiverResult.indexOf(":") + 1);
									mBufferPlayTts.setLength(0);
									isQueAns =false;
									playHciTts(tts);
								}
							}
						}
					},2000);
				}
				
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setRobotInfo();
		initTts();
		init();
		initClientHandler();
		initServerHandler();
		initServer();
		mWifiAdmin = new WifiAdminUtils(MainActivity.this);
		mWifiAdmin.openWifi();
		wifiHotM = WifiHotManager.getInstance(this, this);
		gson = new Gson();
		startCheckNetwordTimer();
		mAsrDao = new DatabaseAsrDao(this);
		PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_meet_again_miss_you);
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				mWifiAdmin.openWifi();
				wifiHotM.scanWifiHot();
				PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_detecting_network);
			}
		}, 3000);
		initHciSys();
		initTtsHci();
		wifiNameShare = SharedPreferenceUtil.getStringValue(this, "wifiName", null);
		wifiPasShare = SharedPreferenceUtil.getStringValue(this, "wifiPas", null);
	}
	
	
	/**
	 *  初始化离线语音合成
	 */
	private void initTtsHci() {
		if(!MyApplication.initTTSResult){
			MyApplication.mHciCloudTtsHelper = HciCloudTtsHelper.getInstance();
			MyApplication.initTTSResult = MyApplication.mHciCloudTtsHelper.init(MainActivity.this);
			if(!MyApplication.initTTSResult){
				ToastUtils.show(MainActivity.this, "语音合成初始化失败");
				Log.e(TAG, "语音合成初始化失败");
			}
				
		}
	}
	private void startOfflineAsr(){
		Intent asrIntent = new Intent(MainActivity.this,AsrOfflineDialog.class);
		startActivity(asrIntent);
	}
	// 设置账号信息等
	private void setRobotInfo() {

		robotId = FileUtils.getRobotId();
		if (robotId == null)
			return;
		switch (robotId) {
		case RobotInfo.RB_ID_001:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_001;
			//robotName = "bb-001";
			break;
		case RobotInfo.RB_ID_002:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_002;
			//robotName = "bb-002";
			break;
		case RobotInfo.RB_ID_003:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_003;
			//robotName = "bb-003";
			break;
		case RobotInfo.RB_ID_004:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_004;
			//robotName = "bb-004";
			break;
		case RobotInfo.RB_ID_005:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_005;
			//robotName = "bb-005";
			break;
		case RobotInfo.RB_ID_006:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_006;
			//robotName = "bb-006";
			break;
		case RobotInfo.RB_ID_007:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_007;
			//robotName = "bb-007";
			break;
		case RobotInfo.RB_ID_008:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_008;
			//robotName = "bb-008";
			break;
		case RobotInfo.RB_ID_009:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_009;
			//robotName = "bb-009";
			break;
		case RobotInfo.RB_ID_010:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_010;
			//robotName = "bb-010";
			break;
		case RobotInfo.RB_ID_011:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_011;
			//robotName = "bb-011";
			break;
		case RobotInfo.RB_ID_012:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_012;
			//robotName = "bb-012";
			break;
		case RobotInfo.RB_ID_013:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_013;
			//robotName = "bb-013";
			break;
		case RobotInfo.RB_ID_014:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_014;
			//robotName = "bb-014";
			break;
		case RobotInfo.RB_ID_015:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_015;
			//robotName = "bb-015";
			break;
		case RobotInfo.RB_ID_016:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_016;
			//robotName = "bb-016";
			break;
		case RobotInfo.RB_ID_017:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_017;
			///robotName = "bb-017";
			break;
		case RobotInfo.RB_ID_018:
			RobotInfo.ROBOT_BLUEADARESS = RobotInfo.RB_ID_BLUETOOTH_018;
			//robotName = "bb-017";
			break;
		default:
			//robotName = "bb";
			RobotInfo.ROBOT_BLUEADARESS = null;
			break;
		}

	}

	@Override
	protected void onStart() {
		super.onStart();

		setVolume();
		locationService = ((MyApplication) getApplication()).locationService;
		locationService.setLocationOption(locationService.getDefaultLocationClientOption());
		locationService.registerListener(mLocationListener);
	}

	// 音量默认初始化为最大值
	private void setVolume() {
		try {
			mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initTts() {
		mTts = SpeechSynthesizer.createSynthesizer(this, null);
		setParam();
	}

	private void setParam() {
		mTts.setParameter(SpeechConstant.PARAMS, null);
		mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);// 设置合成
		mTts.setParameter(SpeechConstant.VOICE_NAME, voicerCloud);// 设置发音人
		mTts.setParameter(SpeechConstant.SPEED, speed);// 设置语速
		mTts.setParameter(SpeechConstant.PITCH, pitch);// 设置音调
		mTts.setParameter(SpeechConstant.VOLUME, volume);// 设置音量
		mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");// 设置播放器音频流类型
	}

	private void initServer() {
		server = SocketServer.newInstance(12345, new ServerMsgListener() {
			Message msg = null;

			@Override
			public void handlerHotMsg(String hotMsg) {
				connected = true;
				Log.i(TAG, "server 初始化成功！");
				msg = clientHandler.obtainMessage();
				msg.obj = hotMsg;
				msg.what = 1;
				serverHandler.sendMessage(msg);
			}

			@Override
			public void handlerErorMsg(String errorMsg) {
				connected = false;
				Log.d(TAG, "server 初始化失败！");
				msg = clientHandler.obtainMessage();
				msg.obj = errorMsg;
				msg.what = 0;
				serverHandler.sendMessage(msg);
			}
		});
		server.beginListen();
	}
	/**
	 * 将问题写入到本地文件call.bnf中
	 * */
    private void writeNowTxt(String nowTxt){
    	String mLocalGrammar = null;
    	try {
    		mLocalGrammar = FileUtils.readCallToSD();
    		if(mLocalGrammar==null){
    			mLocalGrammar = FucUtil.readFile(this, "call.bnf", "utf-8");
    			 FileUtils.wridCalltoSd(mLocalGrammar,false);
    		}
    		String ss = mLocalGrammar.substring(0,mLocalGrammar.lastIndexOf(";"));
            FileUtils.wridCalltoSd(ss+"|"+nowTxt+";",false);
		} catch (Exception e) {
		}
    	
    }
	// client 初始化
	private void initClient() {
		client = SocketClient.newInstance("192.168.43.1", 12345, new ClientMsgListener() {

			Message msg = null;

			@Override
			public void handlerErorMsg(String errorMsg) {
				connected = false;
				Log.d(TAG, "client 初始化失败！");
				msg = clientHandler.obtainMessage();
				msg.obj = errorMsg;
				msg.what = 0;
				clientHandler.sendMessage(msg);

			}

			@Override
			public void handlerHotMsg(String hotMsg) {
				connected = true;
				Log.i(TAG, "client 初始化成功！");
				msg = clientHandler.obtainMessage();
				msg.obj = hotMsg;
				msg.what = 1;
				clientHandler.sendMessage(msg);

			}
		});
		client.connectServer();
	}

	private void init() {
		mImageView = (ImageView) findViewById(R.id.iv_voice);
		mImageView.setOnTouchListener(this);

//		if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
//			Log.e(TAG, "支持 BLE。。。");
//			boolean bl = bindService(new Intent(MainActivity.this, BluetoothBleService.class), Con,
//					Context.BIND_AUTO_CREATE);
//		}
		this.registerReceiver(receiver, Config.getfilter());
		Intent asrIntent = new Intent(MainActivity.this, AsrService.class);
		bindService(asrIntent, ConAsr, Context.BIND_AUTO_CREATE);
		startService(asrIntent);
		Intent wakeIntent = new Intent(MainActivity.this, WakeService.class);
		bindService(wakeIntent, ConWake, Context.BIND_AUTO_CREATE);
		startService(wakeIntent);
		statusText = (TextView) findViewById(R.id.textView2);
		idText = (TextView) findViewById(R.id.textView3);
		if(robotId!=null)
			idText.setText(robotId.toString());
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.iv_voice:
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				
				initDialog();
				startUnderstanding();
				Log.e(TAG, "按下");
				break;
			case MotionEvent.ACTION_UP:
				// case MotionEvent.ACTION_CANCEL:
				if (recordIndicator != null) {
					recordIndicator.dismiss();
					recordIndicator = null;
				}
				if (NetworkUtils.isWifiConnected(MainActivity.this)) {
					PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.stop);
				}
				Log.e(TAG, "放开手");
				break;
			default:
				break;
			}
			break;

		default:
			break;
		}
		return true;
	}

	private void playHciTts(String text){
		if(MyApplication.initTTSResult)
			MyApplication.mHciCloudTtsHelper.synth(text);
		else
			mTts.startSpeaking(text, null);
	}
	protected void startUnderstanding() {
		
		if (NetworkUtils.isWifiConnected(this)&&NetworkUtils.isNetworkAvailable(this)) {
			if (MyApplication.isConnect) {
				wakeService.stopWakeAiJia();
				stopMp();
				PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.start);
				if (mTts != null && mTts.isSpeaking()) {
					mTts.stopSpeaking();
				}
				if (asrService != null)
					asrService.startUnderstanding();

			} else {
				MyApplication.mPostService.openDevice();
				ToastUtils.show(MainActivity.this, "设备未连接，请等待！");
				PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_device_not_connected);
			}

		} else {
			ToastUtils.show(MainActivity.this, "请连接网络！");
			PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_network_disconnection);
		}

	}

	private void initDialog() {
		recordIndicator = new Dialog(MainActivity.this, R.style.like_toast_dialog_style);
		view = new ImageView(MainActivity.this);
		view.setImageResource(R.drawable.voice_01);
		recordIndicator.setContentView(view,
				new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		LayoutParams lp = recordIndicator.getWindow().getAttributes();
		lp.gravity = Gravity.CENTER;
		recordIndicator.show();
	}
/**
 * 接收数据
 */
	@Override
	protected void receiverData(String data) {
		super.receiverData(data);
		//ToastUtils.show(MainActivity.this, "接收到数据"+data);
	}

	private BDLocationListener mLocationListener = new BDLocationListener() {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (null != location && location.getLocType() != BDLocation.TypeServerError&&location.getAddrStr()!=null) {
				locationService.stop();
				mTts.startSpeaking("您当前的位置是" + location.getAddrStr() + "," + location.getLocationDescribe() + "," + "纬度"
						+ location.getLatitude() + "," + "经度" + location.getLongitude(), null);
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				mTts.startSpeaking("GPS有误", null);
			}else{
				mTts.startSpeaking("GPS有误", null);
			}
		}

	};

	/**
	 * 停止音乐播放
	 * 
	 */
	private void stopMp() {
		if (mp != null) {
			if (mp.isPlaying())
				mp.stop();
			mp.release();
			mp = null;
		}
	}

	private String musicUrl;

	private List<DatabaseAsrOfflineBean> asrList;

	private void asrResultParse(final String text) {

		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Log.e(TAG, "解析结果为=" + text);
				// String answer = mAsrDao.findQuestToAnswer(text);
				asrList = mAsrDao.findAllQuestToAnswer();
				if (asrList != null && asrList.size() > 0) {
					Log.i(TAG, "asrList.size()=" + asrList.size());
					for (DatabaseAsrOfflineBean list : asrList) {
						if (text.contains(list.getQuestion())) {
							mTts.startSpeaking(list.getAnswer(), null);
							return;
						}
					}
				}
				if (!TextUtils.isEmpty(text)) {
					String data = JsonParser.parseJsonToNluAnswer(text);
					// Log.i(TAG, data);
					if (TextUtils.isEmpty(data)) {
						int num = (int) (Math.random()*4);
						if(num ==0)
							data = "这个问题，让抱抱再思考一下！";
						else if(num ==1)
							data = "我暂时还不会!";
						else if(num ==2)
							data = "对于这个问题，我有权保持沉默！";
						else 
							data = "";
						
					} else if (data.equals("translation")) {// 翻译
						data = "";
						new translateAsyncTask().execute(new String[] { MyApplication.contentTranslate,
								MyApplication.fromTranslate, MyApplication.toTranslate });
						return;
					} else if (data.equals("address")) {// 位置
						locationService.start();// 开始定位
						return;
					}else if (data.equals("tales")) {// 故事initiation
						PlayMusicTool.getInstance().playMusicToTales( MainActivity.this,VoiceTitle.VOICE_TALES);
						Log.e(TAG, "讲故事");
						return;
					}else if (data.equals("initiation")) {// 启蒙ancient_poetry
						PlayMusicTool.getInstance().playMusicToTales( MainActivity.this,VoiceTitle.VOICE_INITIATION);
						Log.e(TAG, "启蒙");
						return;
					}else if (data.equals("ancient_poetry")) {// 古诗词
						PlayMusicTool.getInstance().playMusicToTales( MainActivity.this,VoiceTitle.VOICE_ANCIENT_LITERATURE);
						Log.e(TAG, "古诗词");
						return;
					}else if (data.equals("children_song")) {// 儿歌
						PlayMusicTool.getInstance().playMusicToTales( MainActivity.this,VoiceTitle.VOICE_CHILDREN_SONG);
						return;
					} else if (data.startsWith("http") && data.endsWith("mp3")) {// 播放音乐
						musicUrl = data;
						new Thread() {
							@Override
							public void run() {
								if (mp == null)
									mp = new MediaPlayer();
								try {
									mp.setDataSource(musicUrl);
									mp.prepare();
									mp.setOnCompletionListener(new OnCompletionListener() {

										@Override
										public void onCompletion(MediaPlayer mp) {
											// startUnderstanding();
											mTts.startSpeaking("歌曲播放完啦", null);
										}
									});
								} catch (IOException ex) {
									ex.printStackTrace();
								}
								mp.start();
							}
						}.start();

						return;
					}
					// 开始播放语音
					int code = mTts.startSpeaking(data, null);

				}
			}
		});
	}

	public class translateAsyncTask extends AsyncTask<String, String, String> {

		String translate = "";
		String to = "en";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			translate = params[0];
			to = params[2];
			String translateStr = null;
			try {
				translateStr = BaiduTranslate.translate(params[0], params[1], params[2]);
				Log.e(">>>>>>>", translateStr);
			} catch (Exception e) {
				translateStr = "翻译失败";
				e.printStackTrace();
			}
			return translateStr;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			// 开始播放语音
			if (to.equals("en")) {
				mTts.startSpeaking(translate + "的英文是" + result, null);
			} else {
				mTts.startSpeaking(translate + "的翻译是" + result, null);
			}

		}

	}

	private void initServerHandler() {
		serverHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Log.e(TAG, "msg.what=" + msg.what);
				if (msg.what == 0) {
				} else {
					String text = (String) msg.obj;
					try {
						ChatMessage chatMsg = gson.fromJson(text, ChatMessage.class);
						wifiName = chatMsg.getWifiName();
						wifiPas = chatMsg.getWifiPassword();

						if (ChineseUtil.checkNameChese(wifiPas)) {// 检查是否是中文
							// 是中文的话，说明是问题和答案，添加到本地数据库中
							Log.i(TAG, "是中文的话，说明是问题和答案，添加到本地数据库中");
							if (mAsrDao.findQuestToAnswer(wifiName) != null) {
								mAsrDao.updateQuestAndAnswer(wifiName, wifiPas);
								ToastUtils.show(MainActivity.this, "提问:" + wifiName + "答案:" + wifiPas);
								//mTts.startSpeaking("更新回答成功!", null);
								playHciTts("更新回答成功!");
								statusText.setText("wifi="+wifiName+":"+wifiPas);
								PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.entertap);
								return;
							}
							ToastUtils.show(MainActivity.this, wifiName+":"+wifiPas);
							playHciTts("新增成功!");
							//mTts.startSpeaking("新增成功!", null);
							mAsrDao.addQuestAndAnswer(wifiName, wifiPas);
							writeNowTxt(wifiName);//加入提问到call中
							statusText.setText("wifi="+"提问:" + wifiName + "  答案:" + wifiPas);
							PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.entertap);
						} else {
							startConnectWifi(wifiName,wifiPas);
						}
						Log.i(TAG, "into initServerHandler() handleMessage(Message msg) text = " + text);

					} catch (Exception e) {
						// TODO: handle exception
					}

				}
			}
		};
	}
	private void startConnectWifi(String wifi ,String pas){
		SharedPreferenceUtil.saveString(MainActivity.this, "wifiName", wifi);
		SharedPreferenceUtil.saveString(MainActivity.this, "wifiPas", pas);
		wifiHotM.closeAWifiHot();// 先关闭热点再根据账号密码连接wifi
		PlayMusicTool.getInstance().playMusicToId(MainActivity.this,R.raw.bb_have_connectting);
		wifiHotM.scanWifiHot();
	}
	private void initClientHandler() {
		clientHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Log.i(TAG, "into initClientHandler() handleMessage(Message msg)");
				if (msg.what == 0) {
					/// statu.setText("连接失败！");
					isContectWifi = false;
				} else {
					// statu.setText("请连接热点deron_baobao!");
					Toast.makeText(MainActivity.this, "请连接热点deron_baobao", 1).show();
					PlayMusicTool.getInstance().playMusicToId(MainActivity.this,
							R.raw.bb_please_reconfigure_the_network);
					isContectWifi = true;
					String text = (String) msg.obj;
					Toast.makeText(MainActivity.this, text, 0).show();
					Log.i(TAG, "into initClientHandler() handleMessage(Message msg) text =" + text);
				}
			}
		};
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 语音合成
		destroyTts();
		MyApplication.mHciCloudTtsHelper.release();
		MyApplication.initTTSResult = false;
		locationService.unregisterListener(mLocationListener); // 注销掉监听
		locationService.stop(); // 停止定位服务
		unregisterReceiver(receiver);
		if (server != null) {
			server.clearServer();
			server.stopListner();
			server = null;
		}
		if (wifiHotM != null) {
			wifiHotM.unRegisterWifiScanBroadCast();
			wifiHotM.unRegisterWifiStateBroadCast();
			wifiHotM.disableWifiHot();
		}
	}

	private  void  stopTts(){
		if (mTts != null) {
			if (mTts.isSpeaking())
				mTts.stopSpeaking();
		}
	}
	private  void  destroyTts(){
		if (mTts != null) {
			if (mTts.isSpeaking())
				mTts.stopSpeaking();
			mTts.destroy();
		}
	}
	// wifi 热点扫描回调
	@Override
	public void disPlayWifiScanResult(List<ScanResult> wifiList) {

		Log.i(TAG, "into 扫描结果回调函数");
		this.wifiList = wifiList;
		wifiHotM.unRegisterWifiScanBroadCast();
		Log.i(TAG, "out 热点扫描结果 ： = " + wifiList);
		Log.i(TAG, "wifiName： = " + wifiName);
		Log.i(TAG, "wifiPas： = " + wifiPas);
		if (wifiList != null && wifiList.size() > 0) {
			//PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_have_network);
			for (ScanResult wifi : wifiList) {
				Log.i(TAG, "wifi.SSID = " + wifi.SSID);
				if(wifiName!=null){
					if (wifi.SSID.equals(wifiName)) {
						Log.i(TAG, "找到网络了");
						PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_have_connectting);
						Toast.makeText(MainActivity.this, "正在连接" + wifiName, 0).show();
						connectWifi(wifi, wifiPas);
					}
				}else{
					if(wifiNameShare!=null){
						if (wifi.SSID.equals(wifiNameShare)) {
							PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_have_connectting);
							Toast.makeText(MainActivity.this, "正在连接wifiNameShare" + wifiNameShare, 0).show();
							connectWifi(wifi, wifiPasShare);
						}
					}
				}
			}
		}

	}

	private void connectWifi(ScanResult scanResult, String pas) {
		String desc = "";
		String descOri = scanResult.capabilities.toUpperCase();
		if (descOri.contains("WPA-PSK")) {
			desc = "WPA";
		}else if (descOri.contains("WPA2-PSK")) {
			desc = "WPA2";
		}else if (descOri.contains("WPA-PSK") && descOri.contains("WPA2-PSK")) {
			desc = "WPA/WPA2";
		}else if (desc.equals("")) {
			isConnectSelf(scanResult);
			return;
		}
		isConnect(scanResult, pas);
	}

	private void isConnect(ScanResult scanResult, String pas) {
		if (mWifiAdmin.isConnect(scanResult)) {
			Toast.makeText(MainActivity.this, "已連接", 0).show();
		} else {
			WifiConnectUtils.WifiCipherType type = null;
			if (scanResult.capabilities.toUpperCase().contains("WPA")) {
				type = WifiConnectUtils.WifiCipherType.WIFICIPHER_WPA;
			} else if (scanResult.capabilities.toUpperCase().contains("WEP")) {
				type = WifiConnectUtils.WifiCipherType.WIFICIPHER_WEP;
			} else {
				type = WifiConnectUtils.WifiCipherType.WIFICIPHER_NOPASS;
			}

			boolean isConnect = mWifiAdmin.connect(scanResult.SSID, pas, type);
		}
	}

	private void isConnectSelf(ScanResult scanResult) {
		if (mWifiAdmin.isConnect(scanResult)) {
			// 已连接，显示连接状态对话框
			Toast.makeText(MainActivity.this, "已連接", 0).show();
		} else {
			boolean iswifi = mWifiAdmin.connectSpecificAP(scanResult);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

	// wifi 连接回调
	@Override
	public boolean disPlayWifiConResult(boolean result, WifiInfo wifiInfo) {

		wifiHotM.setConnectStatu(false);
		wifiHotM.unRegisterWifiStateBroadCast();
		wifiHotM.unRegisterWifiConnectBroadCast();
		initClient();
		Log.i(TAG, "out 热点链接回调函数");
		return false;
	}

	// wifi 热点连接、扫描在Wifi关闭的情况下，回调
	@Override
	public void operationByType(OpretionsType type, String SSID) {
		Log.i(TAG, "into operationByType！type = " + type);
		if (type == OpretionsType.CONNECT) {
			wifiHotM.connectToHotpot(SSID, wifiList, Global.PASSWORD);
		} else if (type == OpretionsType.SCAN) {
			wifiHotM.scanWifiHot();
		}
	}

	private boolean isWifiConnect = false;
	@Override
	public void wifiConnectSUccessfull() {
		ToastUtils.show(MainActivity.this, "wifi连接成功！");
		if(!isWifiConnect){
			isWifiConnect = true;
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					isWifiConnect = false;
				}
			}, 2000);
			PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_network_is_connected);
		}
	}

	@Override
	public void wifiConnectFailed() {
		ToastUtils.show(MainActivity.this, "wifi连接失败！");
		PlayMusicTool.getInstance().playMusicToId(MainActivity.this, R.raw.bb_network_disconnection);
	}

	private Timer timer;
	private TimerTask timerTask;
	private int count = 0;

	public void startCheckNetwordTimer() {
		Log.e(TAG, "正在检测网络！");
		count = 0;
		stopTimer();
		if (timer == null) {
			timer = new Timer();
		}
		if (timerTask == null) {
			timerTask = new TimerTask() {
				@Override
				public void run() {
					count++;
					if (count == 13) {
						stopTimer();
					} else {
						Log.e(TAG, "检测网络" + count);
						if (count == 7) {

							if (!NetworkUtils.isWifiConnected(MainActivity.this)) {
								PlayMusicTool.getInstance().playMusicToId(MainActivity.this,
										R.raw.bb_network_disconnection);
								
							} else {
								PlayMusicTool.getInstance().playMusicToId(MainActivity.this,
										R.raw.bb_network_is_connected);
								stopTimer();
							}
						}

					}
				}
			};
		}
		if (timer != null && timerTask != null) {
			timer.schedule(timerTask, 100, 2500);
		}
	}

	public void stopTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
		}
	}
	
	private void initHciSys() {
        boolean loadResult = AccountInfo.getInstance().loadAccountInfo(this);
        if (loadResult) {
            // 加载信息成功进入主界面
        	//Toast.makeText(getApplicationContext(), "语音互动初始化成功", Toast.LENGTH_LONG).show();
        } else {
            // 加载信息失败，显示失败界面
        	//mLogView.setText("加载灵云账号失败！请在assets/AccountInfo.txt文件中填写正确的灵云账户信息，账户需要从www.hcicloud.com开发者社区上注册申请。");
        	//Toast.makeText(getApplicationContext(), "xxxx"+res[position]+"_"+position, Toast.LENGTH_LONG).show();
        	Toast.makeText(getApplicationContext(), "账号出问题了,请检查下网络", Toast.LENGTH_LONG).show();
            return;
        }
        
        // 加载信息,返回InitParam, 获得配置参数的字符串
        InitParam initParam = getInitParam();
        String strConfig = initParam.getStringConfig();
        Log.i(TAG,"\nhciInit config:" + strConfig);
        
        // 初始化
        int errCode = HciCloudSys.hciInit(strConfig, this);
        if (errCode != HciErrorCode.HCI_ERR_NONE && errCode != HciErrorCode.HCI_ERR_SYS_ALREADY_INIT) {
        	//mLogView.append("\nhciInit error: " + HciCloudSys.hciGetErrorInfo(errCode));
        	Toast.makeText(getApplicationContext(), "可能是账号不对哦", Toast.LENGTH_LONG).show();
            return;
        } else {
        	//mLogView.append("\nhciInit success");
        }

        // 获取授权/更新授权文件 :
        errCode = checkAuthAndUpdateAuth();
        if (errCode != HciErrorCode.HCI_ERR_NONE) {
           //  由于系统已经初始化成功,在结束前需要调用方法hciRelease()进行系统的反初始化
        	//mLogView.append("\nCheckAuthAndUpdateAuth error: " + HciCloudSys.hciGetErrorInfo(errCode));
        	Toast.makeText(getApplicationContext(), "授权到期了么？", Toast.LENGTH_LONG).show();
            HciCloudSys.hciRelease();
            return;
        }
	}
	/**
     * 获取授权
     * 
     * @return true 成功
     */
    private int checkAuthAndUpdateAuth() {
        
    	// 获取系统授权到期时间
        int initResult;
        AuthExpireTime objExpireTime = new AuthExpireTime();
        initResult = HciCloudSys.hciGetAuthExpireTime(objExpireTime);
        if (initResult == HciErrorCode.HCI_ERR_NONE) {
            // 显示授权日期,如用户不需要关注该值,此处代码可忽略
            Date date = new Date(objExpireTime.getExpireTime() * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.CHINA);
            Log.i(TAG, "expire time: " + sdf.format(date));

            if (objExpireTime.getExpireTime() * 1000 > System
                    .currentTimeMillis()) {
                // 已经成功获取了授权,并且距离授权到期有充足的时间(>7天)
                Log.i(TAG, "checkAuth success");
                return initResult;
            }
            
        } 
        
        // 获取过期时间失败或者已经过期
        initResult = HciCloudSys.hciCheckAuth();
        if (initResult == HciErrorCode.HCI_ERR_NONE) {
            Log.i(TAG, "checkAuth success");
            return initResult;
        } else {
            Log.e(TAG, "checkAuth failed: " + initResult);
            return initResult;
        }
    }
	 
    /**
     * 加载初始化信息
     * 
     * @param context
     *            上下文语境
     * @return 系统初始化参数
     */
    private InitParam getInitParam() {
        String authDirPath = this.getFilesDir().getAbsolutePath();

        // 前置条件：无
        InitParam initparam = new InitParam();
        // 授权文件所在路径，此项必填
        initparam.addParam(InitParam.AuthParam.PARAM_KEY_AUTH_PATH, authDirPath);
        // 灵云云服务的接口地址，此项必填
        initparam.addParam(InitParam.AuthParam.PARAM_KEY_CLOUD_URL, AccountInfo.getInstance().getCloudUrl());
        // 开发者Key，此项必填，由捷通华声提供
        initparam.addParam(InitParam.AuthParam.PARAM_KEY_DEVELOPER_KEY, AccountInfo.getInstance().getDeveloperKey());
        // 应用Key，此项必填，由捷通华声提供
        initparam.addParam(InitParam.AuthParam.PARAM_KEY_APP_KEY, AccountInfo.getInstance().getAppKey());

        // 配置日志参数
        String sdcardState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
            String sdPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
            String packageName = this.getPackageName();

            String logPath = sdPath + File.separator + "sinovoice"
                    + File.separator + packageName + File.separator + "log"
                    + File.separator;

            // 日志文件地址
            File fileDir = new File(logPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }

            // 日志的路径，可选，如果不传或者为空则不生成日志
            initparam.addParam(InitParam.LogParam.PARAM_KEY_LOG_FILE_PATH, logPath);
        }

        return initparam;
    }


}
